﻿using System;
using System.Collections.Generic;
using System.Net;
using JetBlack.AuthFeedBus.Adapters;

namespace ExampleSubscriber
{
    class Program
    {
        static void Main(string[] args)
        {
            Client client = new Client();

            // Attempt to connect.
            try
            {
                client.Connect(Dns.GetHostName(), 9124);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to connect to distributor: {0}", ex.Message);
                Environment.Exit(-1);
            }

            client.OnData += OnData;
            client.OnClosed += OnClosed;

            Console.WriteLine("Press <enter> to subscribe ...");
            Console.ReadLine();

            client.AddSubscription("LSE", "VOD");
            client.AddSubscription("LSE", "TSCO");
            client.AddSubscription("LSE", "FOO");
            client.AddSubscription("VTX", "BAY");

            Console.WriteLine("Press <enter> to unsubscribe ...");
            Console.ReadLine();

            client.RemoveSubscription("LSE", "VOD");
            client.RemoveSubscription("LSE", "TSCO");
            client.RemoveSubscription("LSE", "FOO");
            client.RemoveSubscription("VTX", "BAY");

            Console.WriteLine("Press <enter> to quit.");
            Console.ReadLine();

            client.Close();
        }

        static void OnData(string feed, string topic, IDictionary<string, object> data, bool isImage)
        {
            Console.WriteLine("OnData: {0} {1} {2}", feed, topic, isImage);
            if (data == null)
                Console.WriteLine("No Data");
            else
            {
                foreach (var item in data)
                    Console.WriteLine("{0}: {1}", item.Key, item.Value);
            }
        }

        static void OnClosed(bool isAbnormal)
        {
            Console.WriteLine("This client as closed {0}", isAbnormal ? "abnormally" : "normally");
            if (isAbnormal)
                Environment.Exit(-1);
        }
    }
}
